package com.weight.common.generate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
 
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
 
import com.weight.common.enums.ResultEnum;
import com.weight.common.generate.temple.AddHtmlResourceFile;
import com.weight.common.generate.temple.AuthFile;
import com.weight.common.generate.temple.ControllerClassFileMapper;
import com.weight.common.generate.temple.I18nResourceFile;
import com.weight.common.generate.temple.MapperInterfaceFile;
import com.weight.common.generate.temple.MapperSQLResourceFile;
import com.weight.common.generate.temple.MapperXmlResourceFile;
import com.weight.common.generate.temple.MybatisConfigFile;
import com.weight.common.generate.temple.POJOClassFileMapper;
import com.weight.common.generate.temple.ServiceClassFileMapper;
import com.weight.common.generate.temple.ServiceInterfaceFileMapper;
import com.weight.common.generate.temple.queryDetailHtmlResourceFile;
import com.weight.common.generate.temple.queryHtmlResourceFile;
import com.weight.common.util.JsonResultUtil; 
import lombok.extern.slf4j.Slf4j;

/**
* 
* 
*/
@Controller
@Slf4j
@RequestMapping("/generate/generateInfo")
public class GeneratorMapperController {
	private String packageName="0";//包名project
	private String modelName="0";//项目名
	private String tableName="0";//"project_info"; 数据库英文表名
	private String tableCnName="0";//"项目信息表";数据库中文表名
	
	private String souPath ;//"src/main/java";//源路径
	private String htmPath ;// "src/main/resources";HTML路径
	private String packPath;//"com/weight/system"; 文件夹路径
	private String i18nFileName="messages_en_US/messages_zh_CN/messages";		
	private String POJOName="PO/VO";	
	private List<GenerateImp> successList2=null;
	/** 数据库字段名	*/
	private  List<String> 	fieldDOList;
	/**	实体类属性名	*/
	private  List<String>  	fieldENList;
	/**	属性中文名		*/
	private  List<String>  	fieldCNList;
	/**	字段类型		*/
	private  List<String> 	fieldTypeList;
	private String htmPathTempl;
  
	 @RequestMapping(value = "/demo", method = RequestMethod.GET)
		public String demo() {
			return "system/generate/demo";
		}
//	 @RequestMapping(value = "/saveDemo", method = RequestMethod.POST)
	public JsonResultUtil saveDemo(@RequestParam("file") MultipartFile file,@Valid GenerateInfoPath generateInfoPath,BindingResult bindingResult) { 
		
	 
	 
	 return new JsonResultUtil(ResultEnum.SUCCESS, "445565", null);
	}
	 
	 private String uPath="FileUpload";
	 
	 private String logo_path="/demo";
	 
//	 @RequestMapping(value = "/saveDemo", produces = "application/json;charset=UTF-8")  
	 @RequestMapping(value = "/saveDemo", method = RequestMethod.POST)
	 @ResponseBody  
	 public void create(HttpServletRequest request, @RequestParam(value="logo", required=false) MultipartFile logo)
			 throws IllegalStateException, IOException {
//		<pre name="code" class="html">  
//		String uPath = (String)request.getServletContext().getAttribute("uPath");
         File dir = new File(uPath + logo_path);//存放图片路径<span style="white-space:pre"> </span>  
         if(!dir.exists()) {  
             dir.mkdirs();  
         }
//	     .toHexString()
         if(logo != null && !logo.isEmpty()) {  
             int index = logo.getOriginalFilename().lastIndexOf('.');  
             String picName = DigestUtils.md5Hex(UUID.randomUUID().toString()) + logo.getOriginalFilename().substring(index);  
             logo.transferTo(new File(uPath + logo_path + picName));  
//	             group.setLogo(logo_path + picName);  
         }  
	 }   
	 
	 
	 
	 
	 
	 
	@RequestMapping(value = "/addGenerateInfo", method = RequestMethod.GET)
	public String addGenerateInfo() {
		return "system/generate/addGenerateInfo";
	}
	/**
	 * 添加
	 * @param file
	 * @param generateInfoPath
	 * @param bindingResult
	 * @return
	 */
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addGenerateInfo", method = RequestMethod.POST)
	@ResponseBody
	public JsonResultUtil excelImport(@RequestParam("file") MultipartFile file,@Valid GenerateInfoPath generateInfoPath,BindingResult bindingResult) { 
		
		
		if(bindingResult.hasErrors()) {
			log.error("参数不正确 generateInfoPath={}", generateInfoPath);
			return new JsonResultUtil(ResultEnum.EXCEPTION, bindingResult.getFieldError().getDefaultMessage(), null); 
		}
		log.info("generateInfoPath={}",generateInfoPath);
		/** 导入处理*/
		Map<String,Object> map=(Map<String, Object>) import2(file);
		List<GenerateImp> successList=(List<GenerateImp>) map.get("successList");
		
		String message=(String) map.get("message"); 
		System.out.println(successList);
		
		
		
		/** 代码生成   */
		if(successList!=null&&successList.size()>0) {
			addGeneraterMethod(successList,generateInfoPath);
		} 
		
		System.out.println(generateInfoPath.toString());
		return new JsonResultUtil(ResultEnum.SUCCESS, message, null); 
	}
	/**
	 * 导入数据处理  格式转换   数据校验  
	 * @param file
	 * @return
	 */
		public static Map<?, ?> import2(MultipartFile file) {
			
			HashMap<Object, Object> map=new HashMap<>();
			ImportParams importParams = new ImportParams();
			// 数据处理
			IExcelDataHandler<GenerateImp> handler = new GeneraExcelHandler();
			handler.setNeedHandlerFields(new String[] { "中文名" });// 注意这里对应的是excel的列名。也就是对象上指定的列名。
			importParams.setDataHandler(handler);

			// 需要验证
			importParams.setNeedSave(true);
			try {
				ExcelImportResult<GenerateImp> result = ExcelImportUtil.importExcelMore(file.getInputStream(), GenerateImp.class,importParams);
				List<GenerateImp>successList = result.getList();
				List<GenerateImp> failList = result.getFailList();
				log.info("是否存在验证未通过的数据:" + result.isVerifyFail());
				log.info("验证通过的数量:" + successList.size());
				log.info("验证未通过的数量:" + failList.size());
				if(result.isVerifyFail()) {
					map.put("message", "数据校验不通过："+failList.size());
				}
				System.out.println(successList);
//				for (GenerateImp generateImp : successList) {
//					log.info("成功列表信息:" +generateImp.toString());
//				}
//				for (GenerateImp generateImp : failList) {
//					log.info("失败列表信息:" +generateImp.toString());
//				}
				map.put("successList",successList);
				map.put("message","上传信息成功！");
			} catch (IOException e) {
				log.error(e.getMessage(), e);
				map.put("message", e.getMessage());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				map.put("message", e.getMessage());
			} 
			return map;
		} 
		
	
	/**
	 * 代码生成器  *第一章 .		代码生成 
	 * @param successList
	 * @param generateInfoPath
	 */
	 public void addGeneraterMethod(List<GenerateImp> successList,GenerateInfoPath generateInfoPath) {
		List<Integer> indexList=new ArrayList<Integer>();//获取表名 所在位置
		for(int i=0;i<successList.size();i++) {
			if(successList.get(i).getENname()!=null&&successList.get(i).getENname().endsWith("_info")&&successList.get(i).getType()!=null&&successList.get(i).getType().equals("main")) {
				packageName=successList.get(i).getENname().substring(0,successList.get(i).getENname().lastIndexOf("_info")).replaceAll("_", "");
				indexList.add(i);
			}else if(successList.get(i).getENname()!=null&&(successList.get(i).getENname().endsWith("_info")
					||successList.get(i).getENname().endsWith("_ral")||successList.get(i).getENname().endsWith("_log")
					||successList.get(i).getENname().endsWith("_norm"))){
				indexList.add(i);
			}
		}
		System.out.println(generateInfoPath);
		String codeType=generateInfoPath.getCodeType();
		
	/** 静态全局变量初始化*/
		souPath = generateInfoPath.getSouPath();//"src/main/java";//源路径
		htmPath = generateInfoPath.getHtmPath();// "src/main/resources";HTML路径
		packPath = generateInfoPath.getPackPath();//"com/weight/system"; 文件夹路径
		/**1.指定文件生成位置*/		
		souPath=new StringBuilder(souPath).append("/").append(packPath).append("/").append(packageName).toString();//源路径+文件夹路径+项目文件名
		/**2.确定文件相对路径*/		
		packPath=toPackage(new StringBuilder(packPath).append("/").append(packageName).toString());//文件夹路径+项目文件名
		i18nFileName="messages_en_US/messages_zh_CN/messages";		
		POJOName="PO/VO";	
		htmPathTempl=new StringBuilder(htmPath).append("/templates/system/").append(packageName).toString();//htmnl路径
		
	/**根据表名位置循环遍历*/
		if(indexList.size()>0) {
			for(int i=0;i<indexList.size();i++) {
				
				if(i==indexList.size()-1) {
					successList2=successList.subList(indexList.get(i)+1, successList.size());
				}else {
					successList2=successList.subList(indexList.get(i)+1, indexList.get(i+1));
				}
				tableName=successList.get(indexList.get(i)).getENname();
				tableCnName=successList.get(indexList.get(i)).getCNname();
			 	modelName=doToEn(successList.get(indexList.get(i)).getENname().trim().toLowerCase());
			 	
			 	/** 静态全局变量初始化*/
			 	/** 数据库字段名	*/
				 fieldDOList=successList2.stream().map(e -> e.getENname().trim().toLowerCase()).collect(Collectors.toList());
				/**	实体类属性名	*/
				 fieldENList=successList2.stream().map(e -> doToEn(e.getENname().trim().toLowerCase())).collect(Collectors.toList());
				/**	属性中文名		*/
				 fieldCNList=successList2.stream().map(e -> e.getCNname().trim()).collect(Collectors.toList());
				/**	字段类型		*/
				 fieldTypeList=successList2.stream().map(e -> (e.getType()==null?"0":e.getType()).trim().toLowerCase()).collect(Collectors.toList());
					
			 	
			 	/**	前端Add代码生成	 */
				if(codeType.equals("frontAdd")||codeType.equals("all")||codeType.equals("frontall"))
				frontAddStyle();
				
				/**	前端Detail代码生成	 */
				if(codeType.equals("frontDetail")||codeType.equals("all")||codeType.equals("frontall"))
			 	frontDetailStyle();
				
				/**	前端List代码生成	 */
				if(codeType.equals("frontList")||codeType.equals("all")||codeType.equals("frontall"))
			 	frontListStyle();
				
				
				/**	ORM代码生成	 */
				if(codeType.equals("orm")||codeType.equals("all"))
				mapperXmlMethod();
				
				/** 数据层DAO  Mapper代码生成*/
				if(codeType.equals("mapper")||codeType.equals("all"))
				mapperMethod();
				 
				/**实体类POVO代码生成*/
				if(codeType.equals("povo")||codeType.equals("all"))
				povoMethod();
				 
				/**服务层Service代码生成*/
				if(codeType.equals("service")||codeType.equals("all"))
				serviceMethod();
				 
				/***控制层  Controller */
				if(codeType.equals("controller")||codeType.equals("all"))
				controllerMethod(); 
				
				/**	SQL代码生成	 */
				if(codeType.equals("sql")||codeType.equals("all"))
				sqlMethod();

				/**	i18n国际化 代码生成	 */
//			 	if(codeType!=null&&(codeType.equals("i18n")||codeType.equals("all")))
//			 	backi18nMethod();

				/**	mybatis-config.xml配置文件代码生成	 */
			 	if(codeType!=null&&(codeType.equals("mybcon")||codeType.equals("all")))
			 	backMybatisConfiMethod();
				
				/**	后台代码生成	 */
			 	if(codeType!=null&&(codeType.equals("back")||codeType.equals("all")))
			 	backMethod();
			}
		} 
	}
	 /**	前端Add代码生成	 */
	 public void frontAddStyle() {
		 log.info("addmodelName={},htmPath={},packageName={},modelName={},fieldENList={},fieldCNList={}, tableCnName={}",modelName,htmPath,packageName,modelName,fieldENList,fieldCNList, tableCnName);
		 if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
			//add	添加页面
			AddHtmlResourceFile ccf1 = new AddHtmlResourceFile(htmPathTempl,packageName,modelName,fieldENList,fieldCNList, tableCnName);
			try { 
				ccf1.generate();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
		 }
	 }
	 /**	前端Detail代码生成	 */
	 public void frontDetailStyle() {
		 log.info("DetailmodelName={}",modelName);
		 if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
			
			 //queryDetail	查详情
			queryDetailHtmlResourceFile ccf2 = new queryDetailHtmlResourceFile(htmPathTempl,packageName,modelName,fieldENList,fieldCNList, tableCnName);
			try {
				ccf2.generate();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
		 }
	 }
	 /**	前端List代码生成	 */
	 public void frontListStyle() {
		 log.info("modelName={}",modelName);
		 if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
		//queryList 查列表
			queryHtmlResourceFile ccf3 = new queryHtmlResourceFile(htmPathTempl,packageName,modelName,fieldENList,fieldCNList, tableCnName);
			try {
				ccf3.generate();
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
		 }
	 }
	 
	/***
	 *   //后台代码生成
	 * @param modelName
	 * @param POJOName
	 */
//	 public void backMethod(GenerateInfoPath generateInfoPath,String modelName,String tableCnName,
//			 List<GenerateImp> successList2,String packageName,String tableName) {
	 public void backMethod() {
	//前台传递数据路径
//		String souPath = generateInfoPath.getSouPath();//"src/main/java";//源路径
//		String htmPath = generateInfoPath.getHtmPath();// "src/main/resources";HTML路径
//		String packPath = generateInfoPath.getPackPath();//"com/weight/system"; 文件夹路径
//		
//		/**1.指定文件生成位置*/		
//		souPath=new StringBuilder(souPath).append("/").append(packPath).append("/").append(packageName).toString();//源路径+文件夹路径+项目文件名
//		/**2.确定文件相对路径*/		
//		packPath=toPackage(new StringBuilder(packPath).append("/").append(packageName).toString());//文件夹路径+项目文件名
//		
//		String i18nFileName="messages_en_US/messages_zh_CN/messages";		
//		String POJOName="PO/VO";	
//		/** 数据库字段名	*/
//		 List<String> 	fieldDOList=successList2.stream().map(e -> e.getENname().trim().toLowerCase()).collect(Collectors.toList());
//		/**	实体类属性名	*/
//		 List<String>  	fieldENList=successList2.stream().map(e -> doToEn(e.getENname().trim().toLowerCase())).collect(Collectors.toList());
//		/**	属性中文名		*/
//		 List<String>  	fieldCNList=successList2.stream().map(e -> e.getCNname().trim()).collect(Collectors.toList());
//		/**	字段类型		*/
//		 List<String> 	fieldTypeList=successList2.stream().map(e -> (e.getType()==null?"0":e.getType()).trim().toLowerCase()).collect(Collectors.toList());
//			 
//		 htmPath=new StringBuilder(htmPath).append("/templates/system/").append(packageName).toString();//htmnl路径
		if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
	//实体类PO   Entity
//		 	String[] POJONames=POJOName.split("/");
//		 	for(int k=0;k<POJONames.length;k++) {
//				POJOClassFileMapper pcf = new POJOClassFileMapper(souPath+"/"+POJONames[k], packPath, POJONames[k], modelName,fieldENList,fieldCNList,fieldTypeList);
//				try {
//					pcf.generate();
//				} catch (Exception e4) {
//					e4.printStackTrace();
//					log.error(POJOClassFileMapper.class.getPackage()+e4.getMessage(), e4);
//				}
//			}
	//数据层DAO  Mapper
//			MapperInterfaceFile rif = new MapperInterfaceFile(souPath+"/DAO",packPath,"DAO",modelName,tableCnName);
//			try {
//				rif.generate();
//			} catch (Exception e3) {
//				e3.printStackTrace();
//				log.error(e3.getMessage(), e3);
//			}
	//服务层接口	ServiceMapper
//			ServiceInterfaceFileMapper sif = new ServiceInterfaceFileMapper(souPath+"/service",packPath,"service",modelName,tableCnName);
//			try {
//				sif.generate();
//			} catch (Exception e2) {
//				e2.printStackTrace();
//				log.error(e2.getMessage(), e2);
//			}
	//服务层实现	ServiceImplMapper
//			ServiceClassFileMapper scf = new ServiceClassFileMapper(souPath+"/service/impl",packPath,"service.impl",modelName,tableCnName);
//			try {
//				scf.generate();
//			} catch (Exception e1) {
//				e1.printStackTrace();
//				log.error(e1.getMessage(), e1);
//			}

	//控制层  Controller
//			ControllerClassFileMapper ccf = new ControllerClassFileMapper(souPath+"/web",packPath,"web", packageName,modelName,tableCnName,fieldENList.get(0));
//			try {
//				ccf.generate();
//			} catch (Exception e) {
//				e.printStackTrace();
//				log.error(e.getMessage(), e);
//			} 
	//mybatis
//			MapperXmlResourceFile mmf =new MapperXmlResourceFile(htmPath+"/mybatis/mapper",modelName,packPath,fieldDOList,fieldENList,fieldTypeList,tableName,tableCnName);
//			try {
//				mmf.generate();
//			} catch (Exception e6) {
//				e6.printStackTrace();
//				log.error(e6.getMessage(), e6);
//			}
	//mybatis-config.xml配置文件
//			MybatisConfigFile mff=new MybatisConfigFile(htmPath+"/mybatis",modelName,"mybatis-config",packPath,tableCnName);
//			try {
//				mff.geneLine(22L);//mybatis-config.xml
//			} catch (Exception e5) {
//				e5.printStackTrace();
//				log.error(e5.getMessage(), e5);
//			}
	//i18n国际化
//			String[] i18nNames=i18nFileName.split("/");
//			for(int k=0;k<i18nNames.length;k++) {
//				I18nResourceFile mi18f =new I18nResourceFile(htmPath+"/i18n",i18nNames[k],modelName,fieldENList,fieldCNList,tableCnName);
//				try {
//					mi18f.geneAppend();
//				} catch (Exception e4) {
//					e4.printStackTrace();
//					log.error(e4.getMessage(), e4);
//				}
//			}
			
			AuthFile aasd=new AuthFile(htmPath+"/mybatis/sql","pathUrl",modelName,fieldENList,fieldCNList,tableCnName,packageName);
//			(String filePath,String fileName,String model,List<String> fieldENList,List<String> fieldCNList,String tableCnName) {
			try {
				aasd.geneAppend();
			} catch (Exception e4) {
				e4.printStackTrace();
				log.error(e4.getMessage(), e4);
			}
			
	 	}
	 //sql
//	 	MapperSQLResourceFile mqf =new MapperSQLResourceFile(htmPath+"/mybatis/sql",packageName,modelName,successList2,tableName,tableCnName);
//		try {
//			mqf.geneAppend();
//		} catch (Exception e5) {
//			e5.printStackTrace();
//			log.error(e5.getMessage(), e5);
//		}
		 
	 }
	 /***
	 * mybatis-config.xml配置文件代码生成
	 */
	 public void backMybatisConfiMethod() {
//			if(modelName.endsWith("Info")) {
				//mybatis-config.xml配置文件
				MybatisConfigFile mff=new MybatisConfigFile(htmPath+"/mybatis",modelName,"mybatis-config",packPath,tableCnName);
				try {
					mff.geneLine(22L); 
				} catch (Exception e5) {
					e5.printStackTrace();
					log.error(e5.getMessage(), e5);
				} 
//		 	} 
	 }
	 /**
	  * i18n国际化 代码生成
	  */
	 public void backi18nMethod() {
		if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
			//i18n国际化
			String[] i18nNames=i18nFileName.split("/");
			for(int k=0;k<i18nNames.length;k++) {
				I18nResourceFile mi18f =new I18nResourceFile(htmPath+"/i18n",i18nNames[k],modelName,fieldENList,fieldCNList,tableCnName);
				try {
					mi18f.geneAppend();
				} catch (Exception e4) {
					e4.printStackTrace();
					log.error(e4.getMessage(), e4);
				}
			}
	 	}
	 }
	 /**
	  * 实体类POVO代码生成
	  */
	 public void povoMethod() {
		if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
		//实体类PO   Entity
		 	String[] POJONames=POJOName.split("/");
		 	for(int k=0;k<POJONames.length;k++) {
				POJOClassFileMapper pcf = new POJOClassFileMapper(souPath+"/"+POJONames[k], packPath, POJONames[k], modelName,fieldENList,fieldCNList,fieldTypeList,tableCnName);
				try {
					pcf.generate();
				} catch (Exception e4) {
					e4.printStackTrace();
					log.error(POJOClassFileMapper.class.getPackage()+e4.getMessage(), e4);
				}
			}
	 	}else {
			POJOClassFileMapper pcf = new POJOClassFileMapper(souPath+"/PO", packPath, "PO", modelName,fieldENList,fieldCNList,fieldTypeList,tableCnName);
			try {
				pcf.generate();
			} catch (Exception e4) {
				e4.printStackTrace();
				log.error(POJOClassFileMapper.class.getPackage()+e4.getMessage(), e4);
			}
	 	}
	 }
	 /**
	  * 数据层DAO  Mapper代码生成
	  */
	 public void mapperMethod() {
//		if(modelName.endsWith("Info")) {
			//数据层DAO  Mapper
			MapperInterfaceFile rif = new MapperInterfaceFile(souPath+"/DAO",packPath,"DAO",modelName,tableCnName,fieldENList);
			try {
				rif.generate();
			} catch (Exception e3) {
				e3.printStackTrace();
				log.error(e3.getMessage(), e3);
			}
//	 	}
	 }
	 /**
	  * 服务层代码生成
	  */
	 public void serviceMethod() {
//		if(modelName.endsWith("Info")) {
		//服务层接口	ServiceMapper
			ServiceInterfaceFileMapper sif = new ServiceInterfaceFileMapper(souPath+"/service",packPath,"service",modelName,tableCnName,fieldENList);
			try {
				sif.generate();
			} catch (Exception e2) {
				e2.printStackTrace();
				log.error(e2.getMessage(), e2);
			}
		//服务层实现	ServiceImplMapper
			ServiceClassFileMapper scf = new ServiceClassFileMapper(souPath+"/service/impl",packPath,"service.impl",modelName,tableCnName,fieldENList);
			try {
				scf.generate();
			} catch (Exception e1) {
				e1.printStackTrace();
				log.error(e1.getMessage(), e1);
			}
//	 	}
	 }
	 /**
	  * 控制层  Controller
	  */
	 public void controllerMethod() {
		if(modelName.endsWith("Info")||modelName.endsWith("Log")) {
			//控制层  Controller
			ControllerClassFileMapper ccf = new ControllerClassFileMapper(souPath+"/web",packPath,"web", packageName,modelName,tableCnName,fieldENList.get(0),fieldENList,fieldTypeList);
				try {
					ccf.generate();
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e.getMessage(), e);
				} 
	 	}
	 }
	 /**
	  * ORM生成Mybatis
	  */
	 public void mapperXmlMethod() {
		 
//		if(modelName.endsWith("Info")) { 
			//mybatis
			MapperXmlResourceFile mmf =new MapperXmlResourceFile(htmPath+"/mybatis/mapper",modelName,packPath,fieldDOList,fieldENList,fieldTypeList,tableName,tableCnName);
			try {
				mmf.generate();
			} catch (Exception e6) {
				e6.printStackTrace();
				log.error(e6.getMessage(), e6);
			}
//	 	}
	}
	 /**
	  * SQL 生成
	  */
	 public void sqlMethod() {
	 	//sql
	 	MapperSQLResourceFile mqf =new MapperSQLResourceFile(htmPath+"/mybatis/sql",packageName,modelName,successList2,tableName,tableCnName);
		try {
			mqf.geneAppend();
		} catch (Exception e5) {
			e5.printStackTrace();
			log.error(e5.getMessage(), e5);
		}
	 }
	 
	 
	
	
//public void import1(MultipartFile file) {
//	ImportParams importParams = new ImportParams();
//	// 数据处理
////	IExcelDataHandler<User> handler = new UserExcelHandler();
////	handler.setNeedHandlerFields(new String[] { "姓名" });// 注意这里对应的是excel的列名。也就是对象上指定的列名。
////	
////	importParams.setDataHanlder(handler);
//	importParams.setNeedVerfiy(true);// 需要验证
//	try {
//		ExcelImportResult<User> result = ExcelImportUtil.importExcelMore(file.getInputStream(), User.class,importParams);
//
//		List<User> successList = result.getList();
//		List<User> failList = result.getFailList();
//
//		log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
//		log.info("验证通过的数量:" + successList.size());
//		log.info("验证未通过的数量:" + failList.size());
//
//		for (User user : successList) {
//			log.info("成功列表信息:ID=" + user.getId() + user.getName() + "-"
//					+ new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
//		}
//		for (User user : failList) {
//			log.info("失败列表信息:" + user.getName());
//		}
//	} catch (IOException e) {
//		log.error(e.getMessage(), e);
//	} catch (Exception e) {
//		log.error(e.getMessage(), e);
//	}
//}
// 
 	

//
//<form enctype="multipart/form-data" method="post" action="/testuploadimg">
//图片<input type="file" name="file"/>
//<input type="submit" value="上传"/>
//</form>
	//跳转到上传文件的页面
    @RequestMapping(value="/gouploadimg", method = RequestMethod.GET)
    public String goUploadImg() {
        //跳转到 templates 目录下的 uploadimg.html
        return "uploadimg";
    }

    //处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    public @ResponseBody String uploadImg(@RequestParam("file") MultipartFile file,    HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();
        /*System.out.println("fileName-->" + fileName);
        System.out.println("getContentType-->" + contentType);*/
        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        try {
            this.uploadFile(file.getBytes(), filePath, fileName);
        } catch (Exception e) {
            // TODO: handle exception
        }
        //返回json
        return "uploadimg success";
    }
	
    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
        File targetFile = new File(filePath);  
        if(!targetFile.exists()){    
            targetFile.mkdirs();    
        }       
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }
//    6).如果上传的文件大于 1M 时，上传会报错文件太大的错误，在 application.properties 中设置上传文件的参数即可
//    spring.http.multipart.maxFileSize=100Mb
//    spring.http.multipart.maxRequestSize=100Mb
 
    //字符串数据格式转换为List数据（非导入数据）		"项目id,project_info_id;项目名称,project_info_name;"
	public static void Po(String fields,List<String> fieldDOList,List<String> fieldENList,List<String> fieldCNList) {
		String[] ttt=fields.split(";");
		for(int i=0;i<ttt.length;i++) {
			String[] ttt1=ttt[i].split(",");
			String[] ttt2=ttt1[1].trim().split("_");
			StringBuffer userInfoId=new StringBuffer();
			for(int j=0;j<ttt2.length;j++) {
				if(j==0) {
					userInfoId.append(ttt2[j]);
				}else {
					userInfoId.append(getModelClass(ttt2[j]));
				}
			}
			fieldDOList.add(ttt1[1].trim().toLowerCase());
			fieldENList.add(userInfoId.toString().trim());
			fieldCNList.add(ttt1[0].trim());
		}
	}
	//表名转驼峰
	public static String doToEn(String DOString) {
		String[] ttt2=DOString.split("_");
		StringBuffer userInfoId=new StringBuffer();
		for(int j=0;j<ttt2.length;j++) {
			if(j==0) {
				userInfoId.append(ttt2[j]);
			}else {
				userInfoId.append(getModelClass(ttt2[j]));
			}
		} 
		return userInfoId.toString();
	}
	//首字母大写
	public static StringBuilder getModelClass(String modelName) {
	    if(modelName!=null&&!modelName.equals("")) {
	    	char[] ch = modelName.toCharArray();  
		    if (ch[0] >= 'a' && ch[0] <= 'z') {  
		        ch[0] = (char) (ch[0] - 32);  
		    }  
			StringBuilder modelClass = new StringBuilder(new String(ch));
			return modelClass;
	    }else {
	    	return null;
	    }
	}
	//路径  替换  / 为 .
	private static String toPackage(String packPath) {
		return packPath.replaceAll("/", ".");
	}
 
}
